const express = require("express");
const router = express.Router();
var md5 = require("md5");
const User = require("./models/user");
const Topic = require("./models/topic");
const Comment = require("./models/comment");

// 渲染首页
router.get("/", async (req, res, next) => {
  try {
    const topic = await Topic.find();
    res.render("index.html", {
      user: req.session.user,
      topic: topic
    });
  } catch (err) {
    next(err);
  }
});
// 渲染注册页面
router.get("/register", (req, res) => {
  res.render("register.html");
});

// 处理注册页面
router.post("/register", async (req, res, next) => {
  const body = req.body;
  try {
    if (await User.findOne({ email: body.email })) {
      return res.status(200).json({
        err_code: 1,
        message: "邮箱已存在"
      });
    }
    if (await User.findOne({ nickname: body.nickname })) {
      return res.status(200).json({
        err_code: 2,
        message: "昵称已存在"
      });
    }
    body.password = md5(md5(body.password));
    const user = await new User(body).save();

    // 注册成功 使用Session记录用户的登录状态
    req.session.user = user;

    res.status(200).json({
      err_code: 0,
      message: "OK"
    });
  } catch (err) {
    return next(err);
  }
});
// 登录页面
router.get("/login", (req, res) => {
  res.render("login.html");
});
// 处理登录页面
router.post("/login", async (req, res, next) => {
  const body = req.body;
  try {
    const user = await User.findOne({
      email: body.email,
      password: md5(md5(body.password))
    });
    if (user) {
      // 修改登录时间
      user.lastModifiedTime = new Date();
      req.session.user = user;
      await User.findByIdAndUpdate(user.id, user);
      res.status(200).json({
        err_code: 0,
        message: "OK"
      });
    } else {
      res.status(200).json({
        err_code: 1,
        message: "用户名或密码错误"
      });
    }
  } catch (err) {
    return next(err);
  }
});
// 登出
router.get("/logout", (req, res) => {
  // 1 清除session
  // 2. 重定向
  delete req.session.user;
  res.redirect("/login");
});

// 进入设置页面
router.get("/settings/profile", (req, res) => {
  res.render("settings/profile.html", {
    user: req.session.user
  });
});
// 处理设置页面
router.post("/settings/profile", async (req, res, next) => {
  const body = req.body;
  try {
    for (let key in body) {
      req.session.user[key] = body[key];
    }
    const user = await User.findByIdAndUpdate(
      req.session.user._id,
      req.session.user
    );
    if (user) {
      res.status(200).json({
        err_code: 0,
        message: "OK"
      });
    } else {
      res.status(200).json({
        err_code: 1,
        message: "保存失败"
      });
    }
  } catch (err) {
    return next(err);
  }
});

// 去发表新的主题
router.get("/topics/new", (req, res) => {
  res.render("topic/new.html", {
    user: req.session.user
  });
});

// 处理新的主题
router.post("/topics/new", async (req, res, next) => {
  try {
    const body = req.body;
    body.nickname = req.session.user.nickname;
    body.createdTime = new Date();
    body.lastReview = new Date();
    await new Topic(body).save();
    res.status(200).json({
      err_code: 0,
      message: "OK"
    });
  } catch (err) {
    next(err);
  }
});

// 查看主题
router.get("/topics/", async (req, res, next) => {
  try {
    const topic = await Topic.findById(req.query.id)
    topic.viewCount++;
    topic.lastReview = req.session.user.nickname
    await Topic.findByIdAndUpdate(req.query.id, topic)
    const comments = await Comment.find({topicId: topic._id})
    res.render("topic/show.html", {
        user: req.session.user,
        topic: topic,
        comments: comments
      });
  } catch (err) {
    next(err);
  }
});

// 提交评论
router.post("/topics/comment", async (req, res, next) => {
    let body = req.body
    body.commentName = req.session.user.nickname
    try {
        await new Comment(body).save()
        res.status(200).json({
            err_code: 0,
            message: "OK"
          });
    }
    catch (err) {
        next(err)
    }
})
module.exports = router;
